package org.octopus.data.desensitized.core.registry;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.octopus.data.desensitized.core.enumeration.DesensitizedPolicy;
import org.octopus.data.desensitized.core.strategy.DesensitizedStrategy;

/**
 * @author lemon
 * @date 2021/8/28 09:43
 */
public class GlobalDesensitizedStrategyRegistry {

    private static final Map<Class<?>, Map<DesensitizedPolicy, DesensitizedStrategy<?>>> DESENSITIZED_STRATEGIES =
            new ConcurrentHashMap<>(8);

    public static void registerDesensitizedStrategy(DesensitizedStrategy<?> desensitizedStrategy) {
        Map<DesensitizedPolicy, DesensitizedStrategy<?>> desensitizedStrategyMap;

        synchronized (GlobalDesensitizedStrategyRegistry.DESENSITIZED_STRATEGIES) {
            Class<?> dataType = desensitizedStrategy.supportDataType();
            desensitizedStrategyMap = DESENSITIZED_STRATEGIES.get(dataType);

            if (desensitizedStrategyMap == null) {
                desensitizedStrategyMap = new ConcurrentHashMap<>(16);
                DESENSITIZED_STRATEGIES.put(dataType, desensitizedStrategyMap);
            }
        }

        desensitizedStrategyMap.put(desensitizedStrategy.supportPolicy(), desensitizedStrategy);
    }

    public static <T> DesensitizedStrategy<T> obtainDesensitizedStrategy(Class<T> dataType, DesensitizedPolicy policy) {
        if (DESENSITIZED_STRATEGIES.containsKey(dataType)) {
            return (DesensitizedStrategy<T>) DESENSITIZED_STRATEGIES.get(dataType).get(policy);
        }

        return null;
    }
}
